<!-- goods params component -->
<template>
  <div class="params-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="params-main">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="params-cate">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="cate.cateIds"
            :clearable="true"
            :options="cate.cateList"
            :props="cate.casProps"
            @change="handleCasChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParam.addParamDialogVisible = true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="params" border stripe highlight-current-row class="param-val">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- v-for渲染el-tab -->
                <el-tag
                  :key="tag"
                  v-for="tag in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, tag)"
                >{{tag}}</el-tag>
                <!-- 新增参数值输入框 默认隐藏-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 新增输入值按钮 默认显示-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column property="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-row>
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="updateParamDialog(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteParamConfirm(scope.row.attr_id)"
                  >删除</el-button>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParam.addParamDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="attrs" border stripe highlight-current-row class="param-val">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- v-for渲染el-tab -->
                <el-tag
                  :key="tag"
                  v-for="tag in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(scope.row, tag)"
                >{{tag}}</el-tag>
                <!-- 新增参数值输入框 默认隐藏-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 新增输入值按钮 默认显示-->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column property="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-row>
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-edit"
                    @click="updateParamDialog(scope.row)"
                  >编辑</el-button>
                  <el-button
                    type="danger"
                    size="mini"
                    icon="el-icon-delete"
                    @click="deleteParamConfirm(scope.row.attr_id)"
                  >删除</el-button>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数对话框 -->
    <el-dialog
      :title="'添加'+titleName+'对话框'"
      :visible.sync="addParam.addParamDialogVisible"
      width="50%"
      @close="resetParamForm('addParamRef')"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addParam.addParamForm"
        :rules="addParam.addParamFormRules"
        ref="addParamRef"
        label-width="100px"
      >
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="addParam.addParamForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="addParam.addParamDialogVisible = false">取消</el-button>
        <el-button plain @click="resetParamForm('addParamRef')">重置</el-button>
        <el-button type="primary" @click="addParamForm('addParamRef')">提交</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数对话框 -->
    <el-dialog
      :title="'修改'+titleName+'对话框'"
      :visible.sync="updateParam.updateParamDialogVisible"
      width="50%"
      @close="resetParamForm('updateParamRef')"
    >
      <!-- 内容主体 -->
      <el-form
        :model="updateParam.updateParamForm"
        :rules="updateParam.updateParamFormRules"
        ref="updateParamRef"
        label-width="100px"
      >
        <el-form-item :label="titleName" prop="attr_name">
          <el-input v-model="updateParam.updateParamForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="updateParam.updateParamDialogVisible = false">取消</el-button>
        <el-button plain @click="resetParamForm('updateParamRef')">重置</el-button>
        <el-button type="primary" @click="updateParamForm('updateParamRef')">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类对象
      cate: {
        cateList: [],
        casProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover'
        },
        cateIds: []
      },
      activeName: 'many', // 被激活的标签页
      params: [], // 动态参数
      attrs: [], // 静态属性
      // 添加参数对象
      addParam: {
        addParamDialogVisible: false,
        addParamForm: {
          attr_name: ''
        },
        addParamFormRules: {
          attr_name: [
            { required: true, message: '动态参数不能为空', trigger: 'blur' }
          ]
        }
      },
      // 修改参数对象
      updateParam: {
        updateParamDialogVisible: false,
        updateParamForm: {},
        updateParamFormRules: {
          attr_name: [
            { required: true, message: '动态参数不能为空', trigger: 'blur' }
          ]
        }
      }
    }
  },

  created() {
    this.getCateList()
  },
  computed: {
    // 计算属性：通过三级分类选择与否控制添加按钮可用和不可用
    isBtnDisable() {
      return this.cate.cateIds.length !== 3
    },
    // 选中三级分类的ID
    cateId() {
      if (this.cate.cateIds.length === 3) {
        return this.cate.cateIds[2]
      }
      return null
    },
    // 动态计算标题名称
    titleName() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    // 获取分类列表
    getCateList() {
      this.axios.get('categories').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取商品分类列表失败')
        }
        this.cate.cateList = resp.data
        this.$message.success({ message: '获取角色列表成功', duration: 500 })
      })
    },
    // 处理商品分类选择改变
    handleCasChange() {
      if (this.cate.cateIds.length !== 3) {
        return (this.cate.cateIds = [])
      }
      // 发起请求，获取对应三级分类默认动态参数
      this.getPropsOrAttrs()
    },
    // 动态获取参数或者属性
    getPropsOrAttrs() {
      this.axios
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: this.activeName }
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('获取商品分类参数失败')
          }
          resp.data.forEach(item => {
            item.attr_vals =
              item.attr_vals === '' ? [] : item.attr_vals.split(',')
            item.inputVisible = false
            item.inputValue = ''
          })
          if (this.activeName === 'many') {
            this.params = resp.data
          } else if (this.activeName === 'only') {
            this.attrs = resp.data
          } else {
            return this.$message.error('数据有误')
          }
          this.$message.success({
            message: '获取参数或者属性成功',
            duration: 500
          })
        })
    },
    // tab标签页切换
    handleTabClick() {
      if (this.cateId) {
        this.getPropsOrAttrs()
      }
    },
    // 修改参数对话框
    updateParamDialog(param) {
      this.updateParam.updateParamForm = { ...param }
      this.updateParam.updateParamDialogVisible = true
    },
    // 修改参数表单提交
    updateParamForm(paramForm) {
      this.$refs[paramForm].validate(valid => {
        if (!valid) {
          // 校验失败
          return this.$message.error('格式不正确，请重新输入')
        }
        // 校验成功
        // 发送请求
        this.axios
          .put(
            `categories/${this.cateId}/attributes/${this.updateParam.updateParamForm.attr_id}`,
            {
              attr_name: this.updateParam.updateParamForm.attr_name,
              attr_sel: this.updateParam.updateParamForm.attr_sel,
              attr_vals: this.updateParam.updateParamForm.attr_vals
            }
          )
          .then(resp => {
            if (resp.meta.status !== 200) {
              return this.$message.error(`修改${this.titleName}失败`)
            }
            this.getPropsOrAttrs()
            this.$message.success({
              message: `修改${this.titleName}成功`,
              duration: 500
            })
            this.updateParam.updateParamDialogVisible = false
          })
      })
    },
    // 删除参数确认
    deleteParamConfirm(paramId) {
      // 删除确认
      this.$confirm(
        '此操作将会永久删除该' + this.titleName + '，确定要删除吗',
        'Warning',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          // 确认删除，执行删除操作
          this.axios
            .delete(`categories/${this.cateId}/attributes/${paramId}`)
            .then(resp => {
              if (resp.meta.status !== 200) {
                return this.$message.error(`删除${this.titleName}失败`)
              }
              // 成功删除，重新获取数据
              this.getPropsOrAttrs()
              this.$message.success(`删除${this.titleName}成功`)
            })
        })
        .catch(() => {
          // 取消删除
          this.$message.info('已取消删除')
        })
    },
    //  重置添加参数表单
    resetParamForm(paramForm) {
      this.$refs[paramForm].resetFields()
    },
    // 添加参数表单提交
    addParamForm(paramForm) {
      // 校验
      this.$refs[paramForm].validate(valid => {
        if (!valid) {
          // 校验失败
          return this.$message.error('格式不正确，请重新输入')
        }
        // 校验成功
        // 发送请求
        this.axios
          .post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addParam.addParamForm.attr_name,
            attr_sel: this.activeName
          })
          .then(resp => {
            if (resp.meta.status !== 201) {
              return this.$message.error(`添加${this.titleName}失败`)
            }
            this.getPropsOrAttrs()
            this.$message.success({
              message: `添加${this.titleName}成功`,
              duration: 500
            })
            this.addParam.addParamDialogVisible = false
          })
      })
    },
    // 参数值添加确认
    handleInputConfirm(param) {
      if (param.inputValue.trim().length !== 0) {
        let attrVals = [...param.attr_vals]
        attrVals.push(param.inputValue)
        attrVals = attrVals.join(',')
        // 发送添加请求
        this.axios
          .put(`categories/${this.cateId}/attributes/${param.attr_id}`, {
            attr_name: param.attr_name,
            attr_sel: this.activeName,
            attr_vals: attrVals
          })
          .then(resp => {
            if (resp.meta.status !== 200) {
              return this.$message.error(`添加${this.titleName}失败`)
            }
            this.$message.success({
              message: `添加${this.titleName}成功`,
              duration: 500
            })
            param.attr_vals.push(param.inputValue)
            param.inputValue = ''
          })
      }
      param.inputVisible = false
    },
    // 参数值点击显示
    showInput(param) {
      param.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数值项
    handleClose(param, tag) {
      let attrVals = [...param.attr_vals]
      attrVals.splice(param.attr_vals.indexOf(tag), 1)
      attrVals = attrVals.join(',')
      // 发送删除参数值请求
      this.axios
        .put(`categories/${this.cateId}/attributes/${param.attr_id}`, {
          attr_name: param.attr_name,
          attr_sel: this.activeName,
          attr_vals: attrVals
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error(`删除${this.titleName}失败`)
          }
          this.$message.success({
            message: `删除${this.titleName}成功`,
            duration: 500
          })
          param.attr_vals.splice(param.attr_vals.indexOf(tag), 1)
        })
    }
  },

  components: {}
}
</script>

<style lang='scss' scoped>
.params-container {
  .params-main {
    .params-cate {
      margin: 10px 0;
    }
  }
  .param-val {
    margin: 10px 0;
    .el-tag + .el-tag {
      margin-left: 10px;
    }
    .button-new-tag {
      margin-left: 10px;
      height: 32px;
      line-height: 30px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .input-new-tag {
      width: 90px;
      margin-left: 10px;
      vertical-align: bottom;
    }
  }
}
</style>
